package net.thetabx.ftdba;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.thetabx.ftdba.http.HttpData;
import net.thetabx.ftdba.http.HttpManager;
import net.thetabx.ftdba.objects.Message;


public class Shoutbox {
	private RStatus status = RStatus.OK;
	private String pureData;
	
	private int[] messageIdDeleted;
	private List<Message> messageList;
	private List<Message> messageListNew;
    private final int N_MESSAGE_MAX = 31;
	
	public void pullMessages(HttpManager http) {
		HttpData response = http.send("/?section=COMMUNAUTE&module=mod_shoutbox&ajax=1&mod_ajax=1");
		this.processData(response);
	}
	
	private void processData(HttpData data) {
		if(data.getStatus() != RStatus.ENDED) {
			status = data.getStatus();
			return;
		}
		
		messageListNew = null;
		int nNewMessage = -1;
		
		StringBuilder content = data.getContentSb();
		this.pureData = new String(content);
		
		status = RStatus.ANALYZING;
		List<Message> tempMessageList = new ArrayList<Message>(); 
		Pattern p = Pattern.compile("<ul class=\"shout_rowalt\">\\s+<li class=\"time\">(\\d+:\\d+:\\d+)</li>\\s+<li class=\"msg\">\\s+<a class=\"class_(\\d+)\\\" href=\"/\\?section=ACCOUNT_INFOS&amp;hash=(\\w+)\\\">(\\w+)</a> : ([^\\t]+)</li>\\s+</ul>");
		Matcher m = p.matcher(content);
		while(m.find()) {
			tempMessageList.add(new Message(m.group(1), m.group(2), m.group(3), m.group(4), m.group(5)));
		}
		if(tempMessageList.size() == 0) {
			status = RStatus.EMPTY_LIST;
			return;
		}
		
		status = RStatus.COMPARISON;
		if(messageList == null) {
			messageListNew = tempMessageList;
			messageList = tempMessageList;
		}
		else {
			messageListNew = new ArrayList<Message>();
			Message lastMess = messageList.get(0);
			nNewMessage = tempMessageList.indexOf(lastMess);
			System.out.println(nNewMessage);	
			if(nNewMessage == -1) {
				messageListNew = tempMessageList;
				messageList = tempMessageList;
			}
			for(int i = 0; i < nNewMessage; i++) {
				messageListNew.add(tempMessageList.get(i));
			}
		}

		messageIdDeleted = null;
		if(messageList.size() > N_MESSAGE_MAX) {
			int i = 0;
			messageIdDeleted = new int[messageList.size() - N_MESSAGE_MAX];
			while(messageList.size() > N_MESSAGE_MAX) {
				Message msg = messageList.remove(messageList.size() - 1);
				messageIdDeleted[i] = msg.getId();
				i++;
			}
		}
		status = RStatus.ENDED;
	}

	public RStatus getStatus() {
		return status;
	}

	public String getPureData() {
		return pureData;
	}

	public List<Message> getMessageList() {
		return messageList;
	}

	public List<Message> getMessageListNew() {
		return messageListNew;
	}

	public int[] getMessageIdDeleted() {
		return messageIdDeleted;
	}
}
